package com.example.girls.viewModels

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.example.girls.data.Girl
import com.example.girls.data.PhotoItem
import com.example.girls.data.VolleySingleton
import com.google.gson.Gson
import kotlin.math.ceil

/**
 * 为整个activity提供数据
 * */
// 网络状态
enum class NetWorkStatus{
    ERROR,
    COMPLETE,
    CAN_LOAD_MORE,
    LOADING
}
class MyViewModel(application: Application) : AndroidViewModel(application) {

    private val _photoListLiveData = MutableLiveData<List<PhotoItem>>()
    private val _dataStatusLive = MutableLiveData<NetWorkStatus>()
    private val perPage = 20
    private var currentPage = 1
    private var totalPage = 1
    private var isNewQuery = true
    val dataStatusLiveData: LiveData<NetWorkStatus> = _dataStatusLive
    val photoListLiveData: MutableLiveData<List<PhotoItem>> = _photoListLiveData
    var needScrollToTop = true
    var perCurrentPosition = 0
    var currentPosition = 0
    init {
        resetQuery()
    }
    fun fetchData() {
        if (_dataStatusLive.value == NetWorkStatus.LOADING) return
        if (currentPage > totalPage) {
            _dataStatusLive.postValue(NetWorkStatus.COMPLETE)
            return
        }
        _dataStatusLive.postValue(NetWorkStatus.LOADING)
        StringRequest(
            Request.Method.GET,
            getUrl(),
            Response.Listener<String> {
                Gson().fromJson(it, Girl::class.java).apply {
                    totalPage = ceil(total_counts.toDouble() / perPage).toInt()
                    if (isNewQuery) {
                        _photoListLiveData.value = data.toList()
                    } else {
                        _photoListLiveData.value =
                            arrayListOf(_photoListLiveData.value!!, data.toList()).flatten()
                    }
                }
                _dataStatusLive.postValue(NetWorkStatus.CAN_LOAD_MORE)
                isNewQuery = false
                currentPage++
            },
            Response.ErrorListener {
                _dataStatusLive.postValue(NetWorkStatus.ERROR)
                Log.e("myLog", "fetchData: $it")
            }
        ).also {
            VolleySingleton.getInstance(getApplication()).requestQueue.add(it)
        }
    }

    fun resetQuery() {
        currentPage = 1
        totalPage = 1
        isNewQuery = true
        needScrollToTop = true
        _dataStatusLive.postValue(NetWorkStatus.CAN_LOAD_MORE)
        fetchData()
    }

    private fun getUrl(): String =
        "https://gank.io/api/v2/data/category/Girl/type/Girl/page/$currentPage/count/$perPage"
}